package xiao_jin.fantastic_journey.core.common.block;

import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.block.Blocks;
import net.minecraft.block.SnowBlock;
import net.minecraft.registry.tag.FluidTags;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Direction;
import net.minecraft.util.math.random.Random;
import net.minecraft.world.WorldView;
import net.minecraft.world.chunk.light.ChunkLightProvider;
import xiao_jin.fantastic_journey.core.init.ModBlocks;

public class SilicifiedWasteSoil extends Block {
    public SilicifiedWasteSoil() {
        super(Settings.copy(Blocks.GRASS_BLOCK).strength(0.8f).ticksRandomly());
    }

    @Override
    public void randomTick(BlockState state, ServerWorld world, BlockPos pos, Random random) {
        if (!canSurvive(state, world, pos)) {
            world.setBlockState(pos, ModBlocks.WASTE_SOIL.getDefaultState());
        } else {
            BlockState blockState = this.getDefaultState();
            for (int i = 0; i < 4; i++) {
                BlockPos blockPos = pos.add(random.nextInt(3) - 1, random.nextInt(5) - 3, random.nextInt(3) - 1);
                if (world.getBlockState(blockPos).isOf(ModBlocks.WASTE_SOIL) && canSpread(blockState, world, blockPos)) {
                    world.setBlockState(blockPos, blockState);
                }
            }
        }
    }

    private static boolean canSurvive(BlockState state, WorldView world, BlockPos pos) {
        BlockPos upBlockPos = pos.up();
        BlockState upBlockState = world.getBlockState(upBlockPos);
        if (upBlockState.isAir()) {
            return true;
        }
        if (upBlockState.isOf(Blocks.SNOW) && upBlockState.get(SnowBlock.LAYERS) == 1) {
            return true;
        }
        if (upBlockState.getFluidState().getLevel() == 8) {
            return false;
        } else {
            int i = ChunkLightProvider.getRealisticOpacity(world, state, pos, upBlockState, upBlockPos, Direction.UP, upBlockState.getOpacity(world, upBlockPos));
            return i < world.getMaxLightLevel();
        }
    }

    private static boolean canSpread(BlockState state, WorldView world, BlockPos pos) {
        BlockPos blockPos = pos.up();
        return canSurvive(state, world, pos) && !world.getFluidState(blockPos).isIn(FluidTags.WATER);
    }
}
